/*
 * @Date: 2019-10-22 16:30:26 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-04-21 19:01:58
 */

import React, {Component} from 'react';
import {toast, ajax, promptBox, cacheTools, high, getBusinessInfo, formDownload} from 'nc-lightapp-front';
import { getAppPageConfig } from 'src/hrpub/common/utils/utils';
import './index.less';
import EmptyImg from '../../../../../hrpub/common/components/emptyImg/index';
import Header from '../components/Header'
import TableList from '../components/tableList'
import CardList from '../components/cardList'
import FileUpload from '../components/fileUpload'
import AddNew from '../components/AddNew'
import printPage from './functions/print';
import Export from 'src/hrpub/common/utils/exportHtml';
import ViewCard from 'src/hrpub/common/components/card-view';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
// import IsMac from '../../../../public/functions/isMac'
// import {fixedCol} from "../../../../../hrpub/common/utils/utils";
import ApproveDetail from 'uap/common/components/ApproveDetail';
import ApprovalTrans from 'uap/common/components/approvalTrans';
const appcode = getAppPageConfig().appcode, pagecode = getAppPageConfig().pagecode;
let businessInfo = getBusinessInfo() || {};
class ContractRenewal extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.form('dataBase', 'dataBefore', 'dataAfter', 'dataBase_add', 'dataBefore_add', 'dataAfter_add')
            props.use.editTable('dataList', 'psnList')
            props.use.search('listquery')
        }
        this.config = getAppPageConfig();
        this.state = {
            json: {},
            buttons: [],
            tableId: 'dataList',
            cardId: 'dataBase',
            isEmpty: true,
            fromApprove: false,          //判断是否从审批中心过来
            pk_org: '',
            showMode: 'tableList',       // 显示状态，默认是列表
            record: null,
            step: '0',
            info2: null,
            formEditOrigin: '',
            // pk_psndoc_subs: '',
            oid: '',
            conditions: {},
            pageid: '',
            pk_ctrtmngs: '',
            showFlowModal: false,        // 流程历史弹窗
            designateDisplay: false,     //指派
            designateData: '',            //指派人的数据
            otherParams: {}
        }
        // if (window.location.href.match('localhost:3006')) {
        //     window.location.hash = '#/ifr?page=2019';
        // }
        props.createUIDom(this.config, (data) => {
            let template = data.template;
            let oid = template.listquery.oid;
            this.initMeta(template,this, data.button);
            props.button.setButtons(data && data.button ? data.button : {});
            props.meta.setMeta(data && data.template ? data.template : {});
            this.setState({
                oid,
                pageid: data.template.pageid,
                titleName: data.template.name || ''
            })
            if(!this.hasToCard && this.state.fromApprove){
                this.toCardList();
            }
        });
        this.closeApproveDetailModal = this.closeApproveDetailModal.bind(this);
        this.fliterListData = this.fliterListData.bind(this);
        this.submitDesignate = this.submitDesignate.bind(this);
        this.hideDesignate = this.hideDesignate.bind(this);
        this.judgeFromWhere = this.judgeFromWhere.bind(this);
    }
    componentWillMount () {
        let callback = (json, status, inlt) => {
            if (status) {
                this.setState({
                    json
                }, function () {

                })//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: ['sign6011', 'cm6011'], domainName: 'hrcm', callback});
    }
    componentDidMount() {
        this.judgeFromWhere();
        this.props.button.setButtonVisible(['add','edit','delete','history','revoke','submit','refresh','save','cancel','query', 'import', 'launch', 'print', 'export_excel', 'cardview'],false);
    }
    initMeta (template,opt, buttonStg) {
        let that = this;
        let json = this.state.json
        let data = template['dataList'].items
        data.push({
            attrcode: 'handleArea',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000012'], /* 国际化处理： 操作*/
            width: '220px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let data = record.values;
                let approve_state = data.approve_state.value;
                let signtype = data.signtype.value;
                let sign_state = data.sign_state.value;
                if(signtype === '2'){
                    //判断是否电子合同且状态为4时显示发起操作
                    if( sign_state === '4' && approve_state !== '-1'){
                        return (
                            <div>
                                <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                    onClick={opt.launchOpreation.bind(opt,record)}
                                >
                                    {/* 发起 */}
                                    { json['hrcm-000043'] }
                                </span>
                                <span style={{color: '#0073E1', cursor: 'pointer'}}
                                    onClick={opt.historyOpreation.bind(opt,record)}
                                >
                                    {/* 流程历史 */}
                                    { json['hrcm-000044'] }
                                </span>
                            </div>
                        )
                    }else if( sign_state  === '4'){
                        return (
                            <div>
                                <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                    onClick={opt.launchOpreation.bind(opt,record)}
                                >
                                    {/* 发起 */}
                                    { json['hrcm-000043'] }
                                </span>
                            </div>
                        )
                    }else {
                       return that.judgeRowButton(approve_state, opt, record)
                    }
                }else{
                    return that.judgeRowButton(approve_state, opt, record)
                }
            }
        });
        let isFile = buttonStg.filter(item => item.key === 'file') 
        isFile.length > 0 &&  data.push({
            attrcode: 'opr',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000011'], /* 国际化处理： 附件管理*/
            width: '80px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                return (
                    <a style={{cursor: 'pointer'}}>
                        <i className="icon iconfont icon-fujianshenpi" onClick={() => {
                            opt.FileManagement(record);
                        }}/>
                    </a>
                )
            }
        })
    }

    // 判断行操作按钮显示
    judgeRowButton (approve_state, opt, record){
        let { json } = this.state;
        if(approve_state === '-1'){ //自由态
            return (
                <div>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.editOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 编辑*/}
                        { json['hrcm-000001'] }
                    </span>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.deleteOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 删除*/}
                        { json['hrcm-000014'] }
                    </span>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.submitOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 提交*/}
                        { json['hrcm-000047'] }
                    </span>
                </div>
            )
        }else if(approve_state === '2' || approve_state === '3'){ //进行中和提交态
            return (
                <div>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.revokeOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 撤回*/}
                        { json['hrcm-000048'] }
                    </span>
                    <span style={{color: '#0073E1', cursor: 'pointer'}}
                        onClick={opt.historyOpreation.bind(opt,record)}
                    >
                       { /* 国际化处理： 流程历史*/}
                        { json['hrcm-000044'] }
                    </span>
                </div>
            )
        }else if(approve_state === '0' || approve_state === '1'){
            return (
                <div>
                    <span style={{color: '#0073E1', cursor: 'pointer'}}
                        onClick={opt.historyOpreation.bind(opt,record)}
                    >
                       { /* 国际化处理： 流程历史*/}
                        { json['hrcm-000044'] }
                    </span>
                </div>
            )
        }
    }

    // 判断是否从审批中心过来
    judgeFromWhere (){
        const { getUrlParam } = this.props;
        let { pk_org,oid } = this.state;
        let id = getUrlParam('id');
        let status = getUrlParam('status');
        let fromApprove = getUrlParam('scene');
        if (!fromApprove && status) {
            fromApprove = 'approvesce'
        }
        if(fromApprove === 'approvesce'|| fromApprove === 'notice'){
            this.setState({
                fromApprove: true,
                pk_ctrtmng: id,
                status: status,
                pk_org: businessInfo.groupId,
                isEmpty: false
            },()=>{
                if(oid){
                    this.hasToCard = true;
                    this.toCardList();
                }
            })
        }
    }

    // 传进表格的一行数据初始化表单数据显示
    initDataShow (pk_ctrtmng, isEdit) {
        let { pk_org } = this.state;
            let paramObj = {
                pk_org: pk_org,
                appCode: this.config.appcode,
                pageCode: pagecode,
                pk_ctrtmng: pk_ctrtmng
            }
            if (isEdit) {
                paramObj.isEdit = true
            }
            this.refs.cardList.initDataShow(paramObj)
    }
    // 调用头部翻页显示方法
    handlePageInfoChange (props, flag, status) {
        this.refs.header.handlePageInfoChange(props, flag, status)
    }
    // 跳转到卡片页面并显示数据
    toCardList (record, isEdit) {
        let { fromApprove } = this.state;
        this.setBtnVisibleAndDisable('notShowSaveAndCancel');
        this.setState({
            showMode: 'cardList',
            record
        }, () => {
            if( fromApprove ){ //如果为true则是从审批中心过来
                let { pk_ctrtmng } = this.state;
                this.setBtnVisibleAndDisable('approveBtnStatus');
                this.initDataShow(pk_ctrtmng, isEdit);   
            }else{
                let refs= this.refs;
                let pk_ctrtmng = record.values.pk_ctrtmng.value;
                refs['header'].setBackBtnVisible(true)
                let cardPaginationDis = true
                if (isEdit) {
                    cardPaginationDis = false
                }
                refs.header.setCardPaginationVisible(cardPaginationDis, true, pk_ctrtmng);
                this.initDataShow(pk_ctrtmng, isEdit);
            }
            this.setBtnVisibleAndDisable('onlyTableListStatus');
        })
    }
    // 设置卡片翻页容器显示隐藏
    setCardPaginationConDis (cardPaginationDis) {
        this.refs.header.setCardPaginationConDis(cardPaginationDis)
    }
    // 返回当前实在卡片状态还是列表状态
    returnListOrCard () {
        return this.state.showMode
    }

    //打印
    printAction (){
        let { tableId, json } = this.state;
        printPage.call(this,tableId, json);
    }

    //输出
    outputAction (){
        let { tableId, json} = this.state;
        Export(document.querySelector('.u-table-scroll'),
        {
            title: this.state.telName /* 国际化处理： 合同续签申请*/,
            fileName: this.state.telName + json['hrcm-000002'] /* 国际化处理： 数据*/,
            maker: json['hrcm-000004'] /* 国际化处理： 制单人*/,
            date: json['hrcm-000005'] /* 国际化处理： 制表日期*/
        }, {
            data: this.props.editTable.getAllData(tableId).rows,
            meta: this.props.meta.getMeta()[tableId],
            showIndex: false
        });
    }

    // 按钮状态统一管理
    setBtnVisibleAndDisable (code) {
        let {button} = this.props;
        let { showMode } = this.state;
        switch (code) {
            // 只有保存和取消按钮
            case 'onlySaveAndCancelShow':
                button.setButtonVisible({
                    add: false,
                    edit: false,
                    delete: false,
                    revoke: false,
                    history: false,
                    file: false,
                    refresh: false,
                    query: false,
                    save: true,
                    cancel: true,
                    submit: false
                })
                break;
            // 不显示取消和保存按钮，其他都可以点击
            case 'notShowSaveAndCancel':
                button.setButtonVisible({
                    add: true,
                    edit: true,
                    delete: true,
                    // revoke: true,
                    // history: true,
                    file: true,
                    refresh: true,
                    save: false,
                    cancel: false,
                    query: false,
                    import: false,
                    submit: true,
                    // print: true,
                    // export_excel: true
                })
                break;
            case 'addDeleteMakeEffectRefreshQuery':
                button.setButtonVisible({
                    add: true,
                    edit: false,
                    delete: true,
                    revoke: true,
                    history: false,
                    file: false,
                    refresh: true,
                    save: false,
                    cancel: false,
                    query: true,
                    submit: true,
                    // import: true,
                    launch: true,
                    cardview: false
                    // print: true,
                    // export_excel: true
                })
                break;
            case 'notShowAnyBtn':
                button.setButtonVisible({
                    add: false,
                    edit: false,
                    delete: false,
                    file: false,
                    refresh: false,
                    save: false,
                    cancel: false,
                    submit: false,
                    revoke: false,
                    query: false,
                    history: false,
                    import: false,
                    launch: false,
                    print: false,
                    export_excel: false
                })
                break;
            // 只有新增和刷新可以点击，其他按钮不可以
            case 'onlyAddAndRefreshNotDisabled':
                button.setButtonDisabled({
                    add: false,
                    edit: true,
                    delete: true,
                    file: true,
                    refresh: false,
                    save: true,
                    cancel: true,
                    query: false,
                    submit: true,
                    revoke: true,
                    history: true,
                    // import: true,
                    launch: true
                })
                break
            // 所有按钮都可以点
            case 'allBtnEnabled':
                button.setButtonDisabled({
                    add: false,
                    edit: false,
                    delete: false,
                    file: false,
                    refresh: false,
                    save: false,
                    cancel: false,
                    query: false,
                    history: false,
                    submit: false,
                    revoke: false,
                    // import: false,
                    launch: false
                })
                break
            // 只用新增可以点击
            case 'onlyAddBtnEnabled':
                button.setButtonDisabled({
                    add: false,
                    edit: true,
                    delete: true,
                    file: true,
                    refresh: true,
                    save: true,
                    cancel: true,
                    query: false,
                    submit: true,
                    revoke: true
                })
                break
            // 从审批中心过来按钮状态
            case 'approveBtnStatus':
                button.setButtonVisible({
                    add: false, 
                    edit: true, 
                    delete: false, 
                    file: true,
                    refresh: false,
                    save: false,
                    cancel: false,
                    query: false,
                    submit: false,
                    revoke: false,
                    history: false,
                    import: false,
                    export_excel: false,
                    output: false
                })
                break;
            //只在列表页显示
            case 'onlyTableListStatus':
                if( showMode === 'cardList'){
                    button.setButtonVisible({
                        import: false,
                        print: false,
                        export_excel: false
                    })
                }else{
                    button.setButtonVisible({
                        import: true,
                        print: true,
                        export_excel: true
                    })
                }
                break;
            default: break;
        }
    }
    // 按钮操作函数
    BtnOperationFun (btnCode) {
        let refs = this.refs
        switch (btnCode) {
            case 'add':
                this.addOperation()
                break;
            case 'edit':
                this.editOpreation()
                break;
            case 'delete':
                this.deleteOpreation()
                break;
            // case 'Viewbooklet':
            //     this.viewbookletOpreation()
            //     break;
            // case 'Effective':
            //     this.submitOpreation()
            //     break;
            case 'import':
                this.importAction();
                break;
            case 'export_excel':
                this.export_excelAction();
                break;
            case 'file':
                this.FileManagement()
                break;
            case 'refresh':
                this.refreshOpreation('refresh')
                break;
            case 'save':
                this.saveOpreation()
                break;
            case 'cancel':
                this.cancelOpreation()
                break;
            case 'query':
                this.queryOption()
                break;
            case 'submit':
                this.submitOpreation();
                break;
            case 'history':
                this.historyOpreation();
                break;
            case 'revoke':
                this.revokeOpreation();
                break;
            case 'publicity':
                this.openPublicity();
                break;
            case 'launch':
                this.launchOpreation();
                break;
            case 'print':
                this.printAction();
                break;
            case 'output':
                this.outputAction();
                break;
            case 'cardview':
                this.showCardview();
                break;
            default:break;
        }
    }

    //联查卡片
    showCardview (){
        const { form } = this.props;
        let { cardId } = this.state;
        let formData = form.getAllFormValue(cardId).rows;
        // this.cardView.openCardViewModal(formData);
        this.wpsview.openView(formData)
    }

    // 导入
    importAction(){
        var file = document.getElementById('inputFile');
        file.click();
    }

    // 导出
    export_excelAction(){
        formDownload({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngExportTempletAction.do',
            enctype: 2
        })
    }
    // 提交
    // submitOpreation(rewRecord){
    //     const { editTable } = this.props;
    //     let checkedRows = editTable.getCheckedRows('tableList');
    //     if(!!rewRecord){
    //         pk_ctrtmngs.push(rewRecord.values.pk_ctrtmng.value);
    //     }else{
    //         if( !!checkedRows.length ){

    //         }else{
    //             toast({color: 'warning', content: '请选择提交的数据'})
    //         }
    //     }
    //     
    // }

    // 打开公示
    openPublicity (){
        window.top.openNew({appcode: '60654090'});
    }

    // 流程历史
    historyOpreation(rewRecord){
        const { form } = this.props;
        let billid, billtype;
        if (this.state.showMode === 'tableList') {
            let recordData = rewRecord.values;
            billid = recordData.pk_ctrtmng.value;
            billtype = recordData.pk_billtype.value
        } else {
            let formData = form.getAllFormValue('dataBase').rows[0];
            billid = formData.values.pk_ctrtmng.value;
            billtype = formData.values.pk_billtype.value;
        }
        this.setState({
            showFlowModal: true,
            billid,
            billtype
        })
    }

    // 关闭流程历史
    closeApproveDetailModal(){
        this.setState({
            showFlowModal: false
        })
    }
    // 撤回
    revokeOpreation(rewRecord){
        const state = this.state;
        const {json, pk_org, conditions, showMode} = state;
        // debugger
        let pk_ctrtmngs = [];
        let refs = this.refs;
        let pageType = null;
        if (showMode === 'tableList') {
            let {editTable} = this.props;
            if(!!rewRecord){
                pk_ctrtmngs.push(rewRecord.values.pk_ctrtmng.value);
            }else{
                let selectRowsData = editTable.getCheckedRows('dataList');
                let selectRowLen = selectRowsData.length;
                if (selectRowLen === 0) {
                    toast({
                        color: 'warning',
                        content: json['hrcm-000020'] // 请至少选择一条记录
                    });
                    return false
                }
                pk_ctrtmngs = selectRowsData.map(function (item) {
                    return item.data.values.pk_ctrtmng.value
                })
            }
            pageType = 'list'
        } else {
            pk_ctrtmngs.push(state.record.values.pk_ctrtmng.value)
            pageType = 'card'
        }
        let callback = () => {
            ajax({
                url: '/nccloud/hrcm/ctrtmng/CtrtMngRecallAction.do',
                data: {
                    pk_org: pk_org,
                    appCode: this.config.appcode,
                    pk_ctrtmngs
                },
                success: (result) => {
                    if (result.success) {
                        // refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions);
                        toast({color: 'success', content: json['hrcm-000049']});
                        this.refreshOpreation();
                    }
                }
            })
        }
        this.checkDataPermissionAction(pk_ctrtmngs, 'revoke', callback);
    }
    // 附件管理
    FileManagement (rowRecord) {
        let pk_ctrtmng = ''
        if (this.state.showMode === 'tableList') {
            pk_ctrtmng = rowRecord.values.pk_ctrtmng.value
        } else {
            pk_ctrtmng = this.state.record.values.pk_ctrtmng.value
        }
        let callback = () => {
            this.refs.fileUpload.showUploader(pk_ctrtmng)
        }
        let billPks = []
        billPks.push(pk_ctrtmng)
        this.checkDataPermissionAction(billPks, 'attachment', callback)
    }
    // 提交操作
    submitOpreation (rewRecord) {
        // debugger
        let pk_ctrtmngs = []
        let state = this.state
        const {json, pk_org, conditions, showMode} = state
        let refs = this.refs
        let pageType = null
        if (showMode === 'tableList') {
            let {editTable} = this.props;
            if(!!rewRecord){ //行上操作
                pk_ctrtmngs.push(rewRecord.values.pk_ctrtmng.value);
            }else{ //批量操作
                let selectRowsData = editTable.getCheckedRows('dataList')
                let selectRowLen = selectRowsData.length
                if (selectRowLen === 0) {
                    toast({
                        color: 'warning',
                        content: json['hrcm-000020'] // 请至少选择一条记录
                    });
                    return false
                }
                pk_ctrtmngs = selectRowsData.map(function (item) {
                    return item.data.values.pk_ctrtmng.value
                })
            }

            pageType = 'list'
        } else {
            pk_ctrtmngs.push(state.record.values.pk_ctrtmng.value)
            pageType = 'card'
        }
        let dataObj = {
            // baseParam: {step: state.step, info2: state.info2, pageType},
            pk_org: pk_org,
            appCode: this.config.appcode,
            pk_ctrtmngs
        }
        let callback = ()=>{
            this.submitEvent(dataObj)
        };

        this.checkDataPermissionAction(pk_ctrtmngs, 'submit', callback)
    }

    // 提交
    submitEvent (dataObj, designateData = null){
        const {json} = this.state;
        if( !!designateData ){
            dataObj = Object.assign(dataObj, designateData);
        }
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngSubmitAction.do',
            data: dataObj,
            success: (result) => {
                if (result.success) {
                    if (result.data && result.data.content) {
                        this.setState({
                            designateDisplay: true,
                            designateData: result.data.content,
                            dataObj: dataObj
                        })
                        return;
                    }else{
                        toast({
                            color: 'success',
                            content: json['hrcm-000050'] // 提交成功
                        })
                        this.hideDesignate();
                    }
                    this.refreshOpreation();
                }
            }
        })
    }

    //如果有指派调用此方法
    submitDesignate (value){
        let { dataObj } = this.state;
        let designateData = {
            content: value
        }
        this.submitEvent(dataObj, designateData);
    }

    //关闭指派
    hideDesignate (){
        this.setState({
            designateDisplay: false
        })
    }

    // 刷新操作
    refreshOpreation (refresh) {
        let { fromApprove, json } = this.state;
        if (this.state.showMode === 'tableList') {
            this.refs.tableList.queryTableList(this.state.pk_org);
        } else {
            this.toCardList(this.state.record)
            if(!fromApprove){
                this.refs.tableList.queryTableList(this.state.pk_org)
            }
        }
        if(!!refresh && refresh === 'refresh'){
            toast({color: 'success', content: json['hrcm-000016']}) // 刷新成功
        }
    }
    // 刷新列表操作
    refreshTableList () {
        const {pk_org, pk_ctrtmngs, conditions} = this.state
        this.refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions)
    }
    // 取消操作
    cancelOpreation () {
        let json = this.state.json
        promptBox({
            color: 'warning',
            title: json['hrcm-000003'], // 确认继续
            content: json['hrcm-000022'], // 是否确认取消
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['hrcm-000034'], // 是
            cancelBtnName: json['hrcm-000035'], // 否
            beSureBtnClick: this.beSureCancel.bind(this),
            hasCloseBtn:false
        })
    }
    // 点击生效之后的提示
    makeEffectAfterTips (message, title) {
        let json = this.state.json
        promptBox({
            color: 'warning',
            title: title,
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['hrcm-000034'], // 是
            cancelBtnName: json['hrcm-000035'], // 否
            beSureBtnClick: this.submitOpreation.bind(this),
            cancelBtnClick: this.cancelBtnClick.bind(this),  // 取消按钮点击调用函数,非必输
            // closeBtnClick: this.closeBtnClick.bind(this),
            hasCloseBtn:false
        })
    }
    // 点击取消按钮
    cancelBtnClick () {
        this.setState({
            step: '0'
        })
    }
    // 取消操作确认
    beSureCancel () {
        // 将form表单数据重置为原来的数据
        let { fromApprove } = this.state;
        this.refs.cardList.resetMainFormData()
        if (this.state.formEditOrigin === 'list') {
            this.setBtnVisibleAndDisable('addDeleteMakeEffectRefreshQuery')
            this.setState({
                showMode: 'tableList'
            })
            this.refs['header'].setBackBtnVisible(false)
        } else {
            if( fromApprove ){
                this.setBtnVisibleAndDisable('approveBtnStatus');
            }else{
                this.setCardPaginationConDis(true)
                this.setBtnVisibleAndDisable('notShowSaveAndCancel')
            }
        }
    }
    // 选择组织或则删除组织之后的触发函数
    checkOrDeleteOrg (pk_org) {
        // debugger
        // 
        // let pk_psndoc_subs = null
        // if (localStorage.getItem('pageQueryParam')) {
        //     let pageQueryParam = JSON.parse(localStorage.getItem('pageQueryParam'))
        //     if (pageQueryParam.hasOwnProperty('extend')) {
        //         let extend = pageQueryParam.extend
        //         pk_psndoc_subs = extend.pk_psndoc_subs
        //         let copyPageQueryParam = JSON.parse(JSON.stringify(pageQueryParam))
        //         delete copyPageQueryParam.extend
        //         localStorage.setItem('pageQueryParam', JSON.stringify(copyPageQueryParam))
        //     }
        // }
        if (pk_org) {
            this.setState({
                isEmpty: false,
                pk_org: pk_org,
                // pk_ctrtmngs
            },function () {
                this.refs.tableList.queryTableList(pk_org)
            })
            return false
        }
        this.setState({
            isEmpty: true,
            pk_org: pk_org
        }, function () {
            this.setBtnVisibleAndDisable('notShowAnyBtn')
        })
    }
    // 设置是显示列表还是显示卡片
    setCardListVisible (showMode) {
        this.setState({
            showMode
        },()=>{
            this.setBtnVisibleAndDisable('onlyTableListStatus');
        })

    }
    // 新增操作函数
    addOperation () {
        this.refs.addNew.setNewIncreasedDis(true)
    }
    // 编辑、删除、提交、附件校验接口
    checkDataPermissionAction (billPks, opFlag, callback) {
        let { fromApprove } = this.state;
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngCheckDataPermissionAction.do',
            data: {
                appCode: this.config.appcode,
                scene : fromApprove ? 'approvesce' : null,
                billPks,
                opFlag
                // nodeKey: 'contract'
            },
            success: (result) => {
                if (result.success) {
                    callback()
                }
            }
        })
    }
    // 编辑操作方式
    editOpreation (rowRecord) {
        let refs = this.refs;
        if (this.state.showMode === 'tableList') {
            let callback = () => {
                this.toCardList(rowRecord, true)
                this.setState({
                    formEditOrigin: 'list'
                })
                this.setBtnVisibleAndDisable('onlySaveAndCancelShow')
            }
            let pk_ctrtmngs = rowRecord.values.pk_ctrtmng.value
            let billPks = []
            billPks.push(pk_ctrtmngs)
            this.checkDataPermissionAction(billPks, 'edit', callback)
        } else {
            let { fromApprove } = this.state;
            let callback = () => {
                this.setCardPaginationConDis(false);
                refs.cardList.setMainFormEdit();
                this.setState({
                    formEditOrigin: 'card'
                })
                this.setBtnVisibleAndDisable('onlySaveAndCancelShow');
            }
            let pk_ctrtmngs;
            let billPks = [];
            if( fromApprove ){ //判断是否从审批中心过来
                let { pk_ctrtmng } = this.state;
                pk_ctrtmngs = pk_ctrtmng;
            }else{
                // pk_ctrtmngs =  this.props.form.getFormItemsValue('pk_ctrtmng');
                // debugger
                let record = this.state.record;
                pk_ctrtmngs = record.values.pk_ctrtmng.value;
            }
            billPks.push(pk_ctrtmngs);
            this.checkDataPermissionAction(billPks, 'edit', callback);

        }
    }
    // 设置主表单编辑态
    setMainFormEdit () {
        this.refs.cardList.setMainFormEdit()
    }
    // 保存操作
    saveOpreation () {
        // 调用formView的修改保存方法
        let refs = this.refs
        refs.cardList.formViewEditSave()
    }
    // 生效之后刷新表格
    takeEffectAfterRefresh () {
        let refs = this.refs
        let state = this.state
        refs.tableList.queryTableList(state.pk_org)
    }
    // 确认删除的提示
    sureDeleteTips (paramObj) {
        let json = this.state.json
        promptBox({
            color: 'warning',
            title: json['hrcm-000003'], // 确认删除
            content: json['hrcm-000021'], // 确认删除吗？
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['hrcm-000034'], // 是
            cancelBtnName: json['hrcm-000035'], // 否
            beSureBtnClick: this.applyDeleteInterface.bind(this, paramObj),
            hasCloseBtn:false
        })
    }
    // 调用删除接口
    applyDeleteInterface (paramObj) {
        let state = this.state
        const {json, pk_ctrtmngs, pk_org, conditions, showMode} = state
        let refs = this.refs
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngDeleteAction.do',
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    toast({
                        color: 'success',
                        content: json['hrcm-000046'] // 删除成功
                    });
                    if (showMode === 'cardList') {
                        let allpks = cacheTools.get('allpks');
                        if (allpks.length > 1) {
                            let pkIndex = null
                            let indexNow = allpks.indexOf(paramObj['pk_ctrtmngs'][0])
                            if (indexNow === allpks.length - 1) {
                                pkIndex = 'length - 1'
                            } else {
                                pkIndex = indexNow
                            }
                            refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions, pkIndex)
                        } else {
                            refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions)
                            refs.cardList.EmptyAllFormValue()
                        }
                    } else {
                        refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions)
                    }
                }
            }
        })
    }
    // 删除操作
    deleteOpreation (rowRecord) {
        let { json } = this.state;
        let {editTable, form, paramObj} = this.props;
        // let isCard = false;
        let allpks = [];
        // 
        if (this.state.showMode === 'cardList') {
            // isCard = true
            // let formData = form.getAllFormValue(paramObj['mainForm']).rows[0];
            // let  pk_ctrtmng = formData.values.pk_ctrtmng.value;
            let pk_ctrtmng = this.state.record.values.pk_ctrtmng.value;

            allpks.push(pk_ctrtmng)
        } else {
            if (rowRecord) {
                let pk_ctrtmngs2 = rowRecord.values.pk_ctrtmng.value
                allpks.push(pk_ctrtmngs2)
            } else {
                let selectRowsData = editTable.getCheckedRows('dataList')
                if (selectRowsData.length === 0) {
                    toast({
                        color: 'warning',
                        content: json['hrcm-000063'] // 请选择要删除的数据
                    });
                    return false
                }
                allpks = selectRowsData.map(function (item) {
                    let pk_ctrtmng = item.data.values.pk_ctrtmng.value
                    return pk_ctrtmng
                })
            }
        }
        let callback = () => {
            let paramObj = {
                pk_org: this.state.pk_org,
                // modename: 'hi_psndoc_ctrt',
                // isCard: isCard,
                // allpks: allpks,
                pk_ctrtmngs: allpks,
                appCode: this.config.appcode
            }
            this.sureDeleteTips(paramObj)
        }
        this.checkDataPermissionAction(allpks, 'delete', callback)
    }
    // 合同文本操作
    // viewbookletOpreation (rowRecord) {
    //     let json = this.state.json
    //     if (IsMac(json['cm6011-000148'])) {
    //         return false
    //     }
    //     let pk_psndoc_subs = ''
    //     if (this.state.showMode === 'tableList') {
    //         pk_psndoc_subs = rowRecord.values.pk_psndoc_sub.value
    //     } else {
    //         pk_psndoc_subs = this.state.record.values.pk_psndoc_sub.value
    //     }
    //     let paramObj = {
    //         pk_org: this.state.pk_org,
    //         pk_psndoc_subs: pk_psndoc_subs
    //     }
    //     ajax({
    //         url: '/nccloud/hrcm/templet/ContractTextViewAction.do',
    //         data: paramObj,
    //         success: (result) => {
    //             if (result.success) {
    //                 let origin = 'uclient://start/' + window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '')
    //                 window.location.href = origin + result.data
    //             }
    //         }
    //     })
    // }
    // 查询数据
    searchData = () => {
        const {pk_ctrtmngs, pk_org} = this.state
        let conditions = this.props.search.getQueryInfo('listquery',true);
        this.refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions)
    }
    getTime = (time) => {
        this.setState({
            otherParams: time
        })
    }
    // 点击查询按钮
    queryOption () {
        let template = this.props.meta.getMeta();
        let { pk_org } = this.state;
        template["listquery"].items.map(item => {
             // 部门
             if (item.attrcode === 'pk_psnjob.pk_dept') {
                item.queryCondition = () => {
                    return {
                        'pk_hrorg': pk_org
                    }
                }
             }else if(item.attrcode === 'pk_conttext'){
                item.queryCondition = {
                    pk_org: pk_org,
                    GridRefActionExt: 'nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder'
                }
            }
        })
        this.props.meta.setMeta(template, () => {
            this.props.search.openAdvSearch('listquery', true);
        })
    }
    // 点击分页卡片时重置record
    setRecord = (record) => {
        this.setState({
            record
        })
    }

    // 点击发起校验
    launchOpreation(rowRecord){
        let { json } = this.state;
        let {editTable, form, paramObj} = this.props;
        let allpks = [];
        if (this.state.showMode === 'cardList') {
            let pk_ctrtmng = this.state.record.values.pk_ctrtmng.value;
            allpks.push(pk_ctrtmng)
        } else {
            if (rowRecord) {
                let pk_ctrtmngs2 = rowRecord.values.pk_ctrtmng.value
                allpks.push(pk_ctrtmngs2)
            } else {
                let selectRowsData = editTable.getCheckedRows('dataList')
                if (selectRowsData.length === 0) {
                    toast({
                        color: 'warning',
                        content: json['hrcm-000020'] // 请选择要删除的数据
                    });
                    return false
                }
                allpks = selectRowsData.map(function (item) {
                    let pk_ctrtmng = item.data.values.pk_ctrtmng.value
                    return pk_ctrtmng
                })
            }
        }
        let callback = () => {
            let paramObj = {
                pk_org: this.state.pk_org,
                pk_ctrtmngs: allpks,
                appCode: this.config.appcode
            }
            this.launchAction(paramObj)
        }
        this.checkDataPermissionAction(allpks, 'sendstart', callback)

    }
    //发起
    launchAction(paramObj){
        let { json } = this.state;
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngSendStartAction.do',
            data: paramObj,
            success: res => {
                if (res.success && res.data) {
                    toast({
                        color: 'success',
                        content: json['hrcm-000051'] // 发起成功
                    })
                    this.refreshOpreation();
                }
            }
        })
    }

    //筛选单据范围
    fliterListData(conditions){
        let { pk_org, pk_ctrtmngs } = this.state;
        this.refs.tableList.queryTableList(pk_org, pk_ctrtmngs, conditions);
    }

    render() {
        const {delay=true, search} = this.props
        const {NCCreateSearch} = search
        const {oid, pageid, showFlowModal, fromApprove , billtype, billid, pk_org, json, designateDisplay, designateData, otherParams} = this.state
        let config ={
            appCode: this.config.appcode,
            pageCode: this.config.pagecode
        }
        return (
            <div className="contractRenewal nc-single-table nc-bill-card">
                <Header
                    {...this.props}
                    ref='header'
                    fromApprove= {fromApprove}
                    pk_org={pk_org}
                    json = {json}
                    BtnOperationFun={this.BtnOperationFun.bind(this)}
                    checkOrDeleteOrg={this.checkOrDeleteOrg.bind(this)}
                    setCardListVisible={this.setCardListVisible.bind(this)}
                    initDataShow={this.initDataShow.bind(this)}
                    cancelOpreation={this.cancelOpreation.bind(this)}
                    setBtnVisibleAndDisable={this.setBtnVisibleAndDisable.bind(this)}
                    setRecord={this.setRecord}
                    getTime={this.getTime}
                    fliterListData={this.fliterListData}
                    />
                <div className="panelContent">
                    <div className="emptyCon" style={{display: this.state.isEmpty ? 'block' : 'none'}}>
                        <EmptyImg text={this.state.json['hrcm-000017']}/>
                    </div>
                    <div className="listCon" style={{display: this.state.isEmpty ? 'none' : 'block'}}>
                        <div style={{display: this.state.showMode === 'tableList' ? 'block' : 'none'}}>
                            <TableList
                            {...this.props}
                            otherParams={otherParams}
                            returnListOrCard={this.returnListOrCard.bind(this)}
                            ref="tableList"
                            setBtnVisibleAndDisable = {this.setBtnVisibleAndDisable.bind(this)}
                            toCardList={this.toCardList.bind(this)}
                            handlePageInfoChange={this.handlePageInfoChange.bind(this)}
                            setRecord={this.setRecord.bind(this)}/>
                        </div>
                        <div style={{display: this.state.showMode === 'tableList' ? 'none' : 'block'}}>
                            <CardList
                            {...this.props}
                            pageid={pageid}
                            fromApprove= {fromApprove}
                            refreshOpreation={this.refreshOpreation.bind(this)}
                            setCardPaginationConDis={this.setCardPaginationConDis.bind(this)}
                            json={this.state.json}
                            refreshTableList={this.refreshTableList.bind(this)}
                            ref="cardList"
                            takeEffectAfterRefresh={this.takeEffectAfterRefresh.bind(this)}
                            setBtnVisibleAndDisable={this.setBtnVisibleAndDisable.bind(this)}
                            handlePageInfoChange={this.handlePageInfoChange.bind(this)}
                            setRecord={this.setRecord.bind(this)}
                            />
                        </div>
                    </div>
                </div>
                <FileUpload json={this.state.json} ref="fileUpload"/>
                <AddNew
                ref="addNew"
                pkOrg={this.state.pk_org}
                {...this.props}
                {...config}
                pageid={pageid}
                json={this.state.json}
                initDataShow={this.initDataShow.bind(this)}
                returnListOrCard={this.returnListOrCard.bind(this)}
                setMainFormEdit={this.setMainFormEdit.bind(this)}
                refreshTableList={this.refreshTableList.bind(this)}
                setRecord={this.setRecord.bind(this)}
                />
                <div style={{display: "none"}}>
                    {
                        NCCreateSearch('listquery', {
                            clickSearchBtn: ()=>{ this.searchData() },
                            onlyShowAdvArea: false,
                            showAdvSearchPlanBtn: true,
                            saveSearchPlan: true,
                            oid: oid,
                            onlyShowSuperBtn: true
                        })
                    }
                </div>
                <ApproveDetail
                    show={showFlowModal}
                    close={this.closeApproveDetailModal}
                    billtype={billtype}  //billMessage.billtype
                    billid={billid}  //billMessage.billid
                />
                <ViewCard
                    { ...this.props }
                    onRef ={ (ref) => {
                        this.cardView = ref
                    }}
                ></ViewCard>
                <WpsModal
                        {...this.props}
                        onRef ={node => this.wpsview = node}
                        appcode={appcode}
                        pk_org={this.state.pk_org}

                    />
                {/* 指派 */}
                { designateDisplay ? <ApprovalTrans
                    // title={json['hrcm-000069']}/* 国际化处理： 指派*/
                    data={designateData}
                    display={designateDisplay}
                    getResult={this.submitDesignate}
                    cancel={this.hideDesignate}
                /> : null}
                <input
                    type="file"
                    name='file'
                    id="inputFile"
                    style={{display: 'none'}}
                />
            </div>
        );
    }
}
export default ContractRenewal